[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import type {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  19. import { PageView } from '~/components/Page/PageView';
  20. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  21. import type { CrowiRequest } from '~/interfaces/crowi-request';
  22. import type { EditorConfig } from '~/interfaces/editor-settings';
  23. import type { IPageGrantData } from '~/interfaces/page';
  24. import type { RendererConfig } from '~/interfaces/services/renderer';
  25. import type { PageModel, PageDocument } from '~/server/models/page';
  26. import type { PageRedirectModel } from '~/server/models/page-redirect';
  27. import {
  28. useCurrentUser,
  29. useIsLatestRevision,
  30. useIsForbidden, useIsNotFound, useIsSharedUser,
  31. useIsEnabledStaleNotification, useIsIdenticalPath,
  32. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  33. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  34. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  35. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  36. useIsSlackConfigured, useRendererConfig,
  37. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  38. } from '~/stores/context';
  39. import { useEditingMarkdown } from '~/stores/editor';
  40. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  41. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  42. import { useRedirectFrom } from '~/stores/page-redirect';
  43. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  44. import { useSelectedGrant } from '~/stores/ui';
  45. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  46. import loggerFactory from '~/utils/logger';
  47. import { BasicLayout } from '../components/Layout/BasicLayout';
  48. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  49. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  50. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  51. import type { NextPageWithLayout } from './_app.page';
  52. import type { CommonProps } from './utils/commons';
  53. import {
  54. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig,
  55. } from './utils/commons';
  56. declare global {
  57. // eslint-disable-next-line vars-on-top, no-var
  58. var globalEmitter: EventEmitter;
  59. }
  60. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  61. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  62. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  63. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  64. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  65. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  66. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  67. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  68. const logger = loggerFactory('growi:pages:all');
  69. const {
  70. isPermalink: _isPermalink, isTrashPage: _isTrashPage, isCreatablePage,
  71. } = pagePathUtils;
  72. const { removeHeadingSlash } = pathUtils;
  73. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  74. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  75. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  76. {
  77. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  78. return v?.data != null
  79. && v?.data.toObject != null
  80. && v?.meta != null
  81. && isIPageInfoForEntity(v.meta);
  82. },
  83. serialize: (v) => {
  84. return {
  85. data: superjson.stringify(v.data.toObject()),
  86. meta: superjson.stringify(v.meta),
  87. };
  88. },
  89. deserialize: (v) => {
  90. return {
  91. data: superjson.parse(v.data),
  92. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  93. };
  94. },
  95. },
  96. 'IPageToShowRevisionWithMetaTransformer',
  97. );
  98. // GrowiContextualSubNavigation for NOT shared page
  99. type GrowiContextualSubNavigationProps = {
  100. isLinkSharingDisabled: boolean,
  101. }
  102. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  103. const { isLinkSharingDisabled } = props;
  104. const { data: currentPage } = useSWRxCurrentPage();
  105. return (
  106. <div data-testid="grw-contextual-sub-nav">
  107. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  108. </div>
  109. );
  110. };
  111. const PutbackPageModal = (): JSX.Element => {
  112. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  113. return <PutbackPageModal />;
  114. };
  115. type Props = CommonProps & {
  116. pageWithMeta: IPageToShowRevisionWithMeta | null,
  117. // pageUser?: any,
  118. redirectFrom?: string;
  119. // shareLinkId?: string;
  120. isLatestRevision?: boolean,
  121. isIdenticalPathPage?: boolean,
  122. isForbidden: boolean,
  123. isNotFound: boolean,
  124. isNotCreatable: boolean,
  125. // isAbleToDeleteCompletely: boolean,
  126. templateTagData?: string[],
  127. templateBodyData?: string,
  128. isSearchServiceConfigured: boolean,
  129. isSearchServiceReachable: boolean,
  130. isSearchScopeChildrenAsDefault: boolean,
  131. isSlackConfigured: boolean,
  132. // isMailerSetup: boolean,
  133. isAclEnabled: boolean,
  134. // hasSlackConfig: boolean,
  135. drawioUri: string | null,
  136. hackmdUri: string,
  137. noCdn: string,
  138. // highlightJsStyle: string,
  139. isAllReplyShown: boolean,
  140. isContainerFluid: boolean,
  141. editorConfig: EditorConfig,
  142. isEnabledStaleNotification: boolean,
  143. isEnabledAttachTitleHeader: boolean,
  144. // isEnabledLinebreaks: boolean,
  145. // isEnabledLinebreaksInComments: boolean,
  146. adminPreferredIndentSize: number,
  147. isIndentSizeForced: boolean,
  148. disableLinkSharing: boolean,
  149. grantData?: IPageGrantData,
  150. rendererConfig: RendererConfig,
  151. };
  152. const Page: NextPageWithLayout<Props> = (props: Props) => {
  153. // register global EventEmitter
  154. if (isClient() && window.globalEmitter == null) {
  155. window.globalEmitter = new EventEmitter();
  156. }
  157. const router = useRouter();
  158. useCurrentUser(props.currentUser ?? null);
  159. // commons
  160. useEditorConfig(props.editorConfig);
  161. useCsrfToken(props.csrfToken);
  162. // page
  163. useIsLatestRevision(props.isLatestRevision);
  164. useIsContainerFluid(props.isContainerFluid);
  165. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  166. useIsForbidden(props.isForbidden);
  167. useIsNotFound(props.isNotFound);
  168. useIsNotCreatable(props.isNotCreatable);
  169. useRedirectFrom(props.redirectFrom ?? null);
  170. useIsSharedUser(false); // this page cann't be routed for '/share'
  171. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  172. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  173. useIsSearchPage(false);
  174. useTemplateTagData(props.templateTagData);
  175. useTemplateBodyData(props.templateBodyData);
  176. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  177. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  178. useIsSearchServiceReachable(props.isSearchServiceReachable);
  179. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  180. useIsSlackConfigured(props.isSlackConfigured);
  181. // useIsMailerSetup(props.isMailerSetup);
  182. useIsAclEnabled(props.isAclEnabled);
  183. // useHasSlackConfig(props.hasSlackConfig);
  184. useDrawioUri(props.drawioUri);
  185. useHackmdUri(props.hackmdUri);
  186. // useNoCdn(props.noCdn);
  187. useDefaultIndentSize(props.adminPreferredIndentSize);
  188. useIsIndentSizeForced(props.isIndentSizeForced);
  189. useDisableLinkSharing(props.disableLinkSharing);
  190. useRendererConfig(props.rendererConfig);
  191. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  192. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  193. useIsAllReplyShown(props.isAllReplyShown);
  194. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  195. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  196. const { pageWithMeta } = props;
  197. const pageId = pageWithMeta?.data._id;
  198. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  199. const revisionBody = pageWithMeta?.data.revision?.body;
  200. useCurrentPageId(pageId ?? null);
  201. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  202. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  203. useCurrentPathname(props.currentPathname);
  204. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  205. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  206. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  207. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  208. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  209. const { mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
  210. useSetupGlobalSocket();
  211. useSetupGlobalSocketForPage(pageId);
  212. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  213. const shouldRenderPutbackPageModal = pageWithMeta != null
  214. ? _isTrashPage(pageWithMeta.data.path)
  215. : false;
  216. // sync grant data
  217. useEffect(() => {
  218. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  219. mutateSelectedGrant(grantDataToApply);
  220. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  221. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  222. useEffect(() => {
  223. const decodedURI = decodeURI(window.location.pathname);
  224. if (isClient() && decodedURI !== props.currentPathname) {
  225. const { search, hash } = window.location;
  226. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  227. }
  228. }, [props.currentPathname, router]);
  229. // initialize mutateEditingMarkdown only once per page
  230. // need to include useCurrentPathname not useCurrentPagePath
  231. useEffect(() => {
  232. if (props.currentPathname != null) {
  233. mutateEditingMarkdown(revisionBody);
  234. }
  235. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  236. useEffect(() => {
  237. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  238. mutateRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  239. }, [mutateRemoteRevisionId, mutateRevisionIdHackmdSynced, pageWithMeta?.data.revision?._id, pageWithMeta?.data.revisionHackmdSynced]);
  240. const title = generateCustomTitleForPage(props, pagePath);
  241. return (
  242. <>
  243. <Head>
  244. <title>{title}</title>
  245. </Head>
  246. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  247. <header className="py-0 position-relative">
  248. <div id="grw-subnav-container">
  249. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  250. </div>
  251. </header>
  252. <div className="d-edit-none">
  253. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  254. </div>
  255. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  256. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  257. <DisplaySwitcher
  258. pageView={
  259. <PageView
  260. pagePath={pagePath}
  261. initialPage={pageWithMeta?.data}
  262. rendererConfig={props.rendererConfig}
  263. />
  264. }
  265. />
  266. <PageStatusAlert />
  267. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  268. </div>
  269. </>
  270. );
  271. };
  272. type LayoutProps = Props & {
  273. children?: ReactNode
  274. }
  275. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  276. const className = useEditorModeClassName();
  277. // init sidebar config with UserUISettings and sidebarConfig
  278. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  279. return (
  280. <BasicLayout className={className}>
  281. {children}
  282. </BasicLayout>
  283. );
  284. };
  285. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  286. return (
  287. <>
  288. <DrawioViewerScript />
  289. <Layout {...page.props}>
  290. {page}
  291. </Layout>
  292. <UnsavedAlertDialog />
  293. <DescendantsPageListModal />
  294. <DrawioModal />
  295. <HandsontableModal />
  296. <TemplateModal />
  297. </>
  298. );
  299. };
  300. function getPageIdFromPathname(currentPathname: string): string | null {
  301. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  302. }
  303. class MultiplePagesHitsError extends ExtensibleCustomError {
  304. pagePath: string;
  305. constructor(pagePath: string) {
  306. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  307. this.pagePath = pagePath;
  308. }
  309. }
  310. // apply parent page grant fot creating page
  311. async function applyGrantToPage(props: Props, ancestor: any) {
  312. await ancestor.populate('grantedGroup');
  313. const grant = {
  314. grant: ancestor.grant,
  315. };
  316. const grantedGroup = ancestor.grantedGroup ? {
  317. grantedGroup: {
  318. id: ancestor.grantedGroup.id,
  319. name: ancestor.grantedGroup.name,
  320. },
  321. } : {};
  322. props.grantData = Object.assign(grant, grantedGroup);
  323. }
  324. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  325. const { model: mongooseModel } = await import('mongoose');
  326. const req: CrowiRequest = context.req as CrowiRequest;
  327. const { crowi } = req;
  328. const { revisionId } = req.query;
  329. const Page = crowi.model('Page') as PageModel;
  330. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  331. const { pageService } = crowi;
  332. let currentPathname = props.currentPathname;
  333. const pageId = getPageIdFromPathname(currentPathname);
  334. const isPermalink = _isPermalink(currentPathname);
  335. const { user } = req;
  336. if (!isPermalink) {
  337. // check redirects
  338. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  339. if (chains != null) {
  340. // overwrite currentPathname
  341. currentPathname = chains.end.toPath;
  342. props.currentPathname = currentPathname;
  343. // set redirectFrom
  344. props.redirectFrom = chains.start.fromPath;
  345. }
  346. // check whether the specified page path hits to multiple pages
  347. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  348. if (count > 1) {
  349. throw new MultiplePagesHitsError(currentPathname);
  350. }
  351. }
  352. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  353. const page = pageWithMeta?.data as unknown as PageDocument;
  354. // add user to seen users
  355. if (page != null && user != null) {
  356. await page.seen(user);
  357. }
  358. // populate & check if the revision is latest
  359. if (page != null) {
  360. page.initLatestRevisionField(revisionId);
  361. await page.populateDataToShowRevision();
  362. props.isLatestRevision = page.isLatestRevision();
  363. }
  364. if (page == null && user != null) {
  365. const templateData = await Page.findTemplate(props.currentPathname);
  366. if (templateData != null) {
  367. props.templateTagData = templateData.templateTags as string[];
  368. props.templateBodyData = templateData.templateBody as string;
  369. }
  370. // apply pagrent page grant
  371. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  372. if (ancestor != null) {
  373. await applyGrantToPage(props, ancestor);
  374. }
  375. }
  376. props.pageWithMeta = pageWithMeta;
  377. }
  378. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  379. const req: CrowiRequest = context.req as CrowiRequest;
  380. const { crowi } = req;
  381. const Page = crowi.model('Page') as PageModel;
  382. const { currentPathname } = props;
  383. const pageId = getPageIdFromPathname(currentPathname);
  384. const isPermalink = _isPermalink(currentPathname);
  385. const page = props.pageWithMeta?.data;
  386. if (props.isIdenticalPathPage) {
  387. props.isNotCreatable = true;
  388. }
  389. else if (page == null) {
  390. props.isNotFound = true;
  391. props.isNotCreatable = !isCreatablePage(currentPathname);
  392. // check the page is forbidden or just does not exist.
  393. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  394. props.isForbidden = count > 0;
  395. }
  396. else {
  397. props.isNotFound = page.isEmpty;
  398. props.isNotCreatable = false;
  399. props.isForbidden = false;
  400. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  401. if (isPermalink && page.isEmpty) {
  402. props.currentPathname = page.path;
  403. }
  404. // /path/to/page ==> /62a88db47fed8b2d94f30000
  405. if (!isPermalink && !page.isEmpty) {
  406. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  407. if (!isToppage) {
  408. props.currentPathname = `/${page._id}`;
  409. }
  410. }
  411. }
  412. }
  413. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  414. // const req: CrowiRequest = context.req as CrowiRequest;
  415. // const { crowi } = req;
  416. // const UserModel = crowi.model('User');
  417. // if (isUserPage(props.currentPagePath)) {
  418. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  419. // if (user != null) {
  420. // props.pageUser = JSON.stringify(user.toObject());
  421. // }
  422. // }
  423. // }
  424. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  425. const req: CrowiRequest = context.req as CrowiRequest;
  426. const { crowi } = req;
  427. const {
  428. searchService, configManager, aclService,
  429. } = crowi;
  430. props.isSearchServiceConfigured = searchService.isConfigured;
  431. props.isSearchServiceReachable = searchService.isReachable;
  432. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  433. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  434. // props.isMailerSetup = mailService.isMailerSetup;
  435. props.isAclEnabled = aclService.isAclEnabled();
  436. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  437. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  438. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  439. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  440. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  441. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  442. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  443. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  444. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  445. props.editorConfig = {
  446. upload: {
  447. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  448. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  449. },
  450. };
  451. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  452. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  453. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  454. props.rendererConfig = {
  455. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  456. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  457. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  458. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  459. plantumlUri: process.env.PLANTUML_URI ?? null,
  460. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  461. // XSS Options
  462. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  463. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  464. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  465. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  466. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  467. };
  468. }
  469. /**
  470. * for Server Side Translations
  471. * @param context
  472. * @param props
  473. * @param namespacesRequired
  474. */
  475. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  476. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  477. props._nextI18Next = nextI18NextConfig._nextI18Next;
  478. }
  479. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  480. const req = context.req as CrowiRequest<IUserHasId & any>;
  481. const { user } = req;
  482. const result = await getServerSideCommonProps(context);
  483. // check for presence
  484. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  485. if (!('props' in result)) {
  486. throw new Error('invalid getSSP result');
  487. }
  488. const props: Props = result.props as Props;
  489. if (props.redirectDestination != null) {
  490. return {
  491. redirect: {
  492. permanent: false,
  493. destination: props.redirectDestination,
  494. },
  495. };
  496. }
  497. if (user != null) {
  498. props.currentUser = user.toObject();
  499. }
  500. try {
  501. await injectPageData(context, props);
  502. }
  503. catch (err) {
  504. if (err instanceof MultiplePagesHitsError) {
  505. props.isIdenticalPathPage = true;
  506. }
  507. else {
  508. throw err;
  509. }
  510. }
  511. await injectRoutingInformation(context, props);
  512. injectServerConfigurations(context, props);
  513. await injectNextI18NextConfigurations(context, props, ['translation']);
  514. return {
  515. props,
  516. };
  517. };
  518. export default Page;